package respository

import (
	"errors"
	"gorm.io/gorm"
	"vpom_-system/model/database"
)

type UserRepository struct{}

func NewUserRepository() *UserRepository {
	return &UserRepository{}
}

func (userRepository *UserRepository) Check(Db *gorm.DB, Name string) error {
	if err := Db.Model(&database.User{}).Where("username = ?", Name).First(&database.User{}).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		return err
	}
	return nil
}

func (userRepository *UserRepository) Add(Db *gorm.DB, user database.User) error {
	if err := Db.Create(&user).Error; err != nil {
		return err
	}
	return nil
}

func (userRepository *UserRepository) Find(Db *gorm.DB, Name string) (database.User, error) {
	var user database.User
	if err := Db.Where("username = ?", Name).First(&user).Error; err != nil {
		return user, err
	}
	return user, nil
}

func (userRepository *UserRepository) Update(Db *gorm.DB, user database.User) error {
	if err := Db.Model(&database.User{}).Where("username = ?", user.Username).Updates(&user).Error; err != nil {
		return err
	}
	return nil
}
